package com.ka.component;

import java.util.ArrayList;
import java.util.List;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.ka.androidapplication.R;

public class LoginForm extends AbsForm {

	protected Button login;
	protected Button register;
	protected TextView forgot_password;
	protected TextView error_space;
	protected List<IFieldValidation> validateList;

	public LoginForm(View v) {
		super(v);

		validateList = new ArrayList<IFieldValidation>();
		initializeUI();

	}

	@Override
	protected void initializeUI() {

		login = (Button) content.findViewById(R.id.login_btn);
		login.setOnClickListener(login_click);

		register = (Button) content.findViewById(R.id.login_register_btn);
		register.setOnClickListener(register_click);

		error_space = (TextView) content.findViewById(R.id.error_space);

		forgot_password = (TextView) content
				.findViewById(R.id.login_forgot_password);

		EditText user_name = (EditText) content
				.findViewById(R.id.login_user_name);
		EditText password = (EditText) content
				.findViewById(R.id.login_password);

		IFieldValidation userField = new UserNameValidation(user_name, true);
		IFieldValidation passField = new PasswordValidation(password, true);

		validateList.add(userField);
		validateList.add(passField);

	}

	OnClickListener login_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			submit();
		}

	};

	OnClickListener register_click = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// open register form
		}

	};

	@Override
	protected void submit() {

		Log.d("Submit", "clear message error");

		messageError.clear();
		error_space.setText("");

		Log.d("Submit error space", error_space.getText().toString());

		validate();
		List<String> errorList = messageError.outMessage();

		Log.d("Submit error number", errorList.size() + "");

		if (errorList.size() == 0) {
			// throw pass it all
			Toast.makeText(content.getContext(), "Pass", Toast.LENGTH_SHORT)
					.show();
		} else {
			// show error list
			error_space.setText(StringUtils.merge(errorList, '*'));
		}

	}

	@Override
	protected void validate() {

		for (IFieldValidation field : validateList) {
			messageError.takeMessageFromOtherMessage(field.validate());
		}

	}

}
